import { BundleConfig } from './BundleConfig';
import UIBase from '../UIFramework/UIBase';
import DataBaseMgr from '../Data/DataBaseMgr';
import DataMgr from '../Data/DataMgr';
import ResMgr from '../Res/ResMgr';

const { ccclass, property } = cc._decorator;

@ccclass
export default class UILoading extends UIBase {
    @property({ visible: true, displayName: "第一个页面", tooltip: "设置第一个打开的页面" })
    private _firstUIName: string = "";
    private _LoadingBar: cc.ProgressBar = null;
    private _Lb: cc.Label = null;
    private _totalCount: number = 0;
    private _curCount: number = 0;
    onInit(...rest: any[]): void {
        this._LoadingBar = this.getComp("_LoadingBar", "ProgressBar");
        this._Lb = this.getComp("_Lb", "Label");
        this._countResTotal();
        this._loadRes();
    }


    private _countResTotal() {
        //通过遍历bundleConfig中的内容，计算需要加载的所有资源
        for (let key in BundleConfig) {
            if (key == "UIFramework") {
                continue;
            }
            let urls = BundleConfig[key].urls;
            for (let url of urls) {
                this._totalCount++;
            }
        }
    }

    private async _loadRes() {
        for (let key in BundleConfig) {
            if (key == "UIFramework") {
                continue;
            }
            let urls = BundleConfig[key].urls;
            for (let url of urls) {
                await ResMgr.instance.loadRes(key, url).then(asset => {
                    if (asset instanceof cc.JsonAsset) {
                        //如果是JsonAsset类型，代表是数据，就直接创建一个数据管理者，并且将数据存入到数据管理者的容器中
                        let mgr = new DataBaseMgr();
                        mgr.addData(asset);
                        //将这个管理者存入到存储管理者的容器中,.并且以数据的名字加上Mgr为管理者的名字
                        DataMgr.instance.addMgr(asset.name + "Mgr", mgr);
                    }
                })
                this._curCount++;
                let progress = this._curCount / this._totalCount;
                this._LoadingBar.progress = progress;
                this._Lb.string = "已加载" + (progress * 100).toFixed(2) + "%";
                if (progress >= 1) {
                    //切换页面
                    this.openUI(this._firstUIName, true, true);
                }
            }
        }
    }

}


